# coding=UTF-8

import os
import re
import cv2
import numpy as np
#from win32api import GetSystemMetrics
SCREEN_WIDTH=1280
SCREEN_HEIGTH=720


def read_dir_files(path):
    fileList=[]
    files = os.listdir(path)
    p = re.compile('[a-zA-Z0-9_]+\.jpg',re.UNICODE)

    for f in files:
        if p.match(f):
            fileList.append(f)
    return fileList


def disp_keypoints(img,kps):
    tmpImg = cv2.drawKeypoints(img, kps,None)
    while (True):
        cv2.imshow("matches", tmpImg)
        if cv2.waitKey() & 0xff == ord("q"):
            break
    cv2.destroyAllWindows()
    return


def disp_matches(img1,img2,kp1,kp2, matches):
    img=cv2.drawMatches(img1, kp1, img2, kp2, matches, None, flags=2)
    sc_width=SCREEN_WIDTH
    sc_height=SCREEN_HEIGTH
    height,width=img.shape[:2]
    if sc_width<width:
        factor=sc_width/width
        dist_height=factor*height
    if sc_height<dist_height:
        factor=sc_height/height
    factor=factor*0.8
    dist_height=int(factor*height)
    dist_width=int(factor*width)
    img=cv2.resize(img,(dist_width,dist_height))


    while (True):
        cv2.imshow("matches",img)
        if cv2.waitKey() & 0xff == ord("q"):
            break
    cv2.destroyAllWindows()
    return

"""
从E矩阵分解出R和t
because of ambiguity,there are two possible solutions for R and t
"""
def decomposeE2RandT(E):
    U,S,Vt=np.linalg.svd(E) ##SVD分解
    ##检查第一个和第二个奇异值是否相等，第三个奇异值为零
    #实际检查时，取第一个和第二个奇异值的比率，应该接近为1
    ratio=S[0]/S[1]
    if ratio>1.0: ratio=1.0/ratio   #使得比率在[0,1]之间
    if ratio<0.7:       ##不正确的E矩阵
        return False,None,None,None,None
    W=np.array([[0,-1,0],       #参见MVG的9.13小节
                [1,0,0],
                [0,0,1]])
    Wt=np.array([[0,1,0],
                 [-1,0,0],
                 [0,0,1]])
    R1=np.dot(U,np.dot(W,Vt))
    R2=np.dot(U,np.dot(Wt,Vt))
    t1=U[:,2]
    t2=-U[:,2]
    return True,R1,R2,t1,t2
